package com.ywu.boot.interceptor.impl;

import com.ywu.boot.config.BootConfigAppConfig;
import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.boot.context.YwuContextTenant;
import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.boot.interceptor.ContextBuilderInterface;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.utils.AesUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName UserTenantContextBuilder
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/5/26 20:53
 * @Version 1.0
 **/
@Component
@Slf4j
@Order(6)
public class UserTenantContextBuilder implements ContextBuilderInterface {
    private static final String TENANT_ID_HEADER_KEY = "X-Pix-Ywu-Tenant-Info";

    @Autowired
    private BootConfigAppConfig appConfig;

    @Override
    public void buildContext(HttpServletRequest request, HttpServletResponse response) {
        String tenantInfo = request.getHeader(TENANT_ID_HEADER_KEY);
        // 解析上下文中加密的数据
        try {
            if (StringUtils.isEmpty(tenantInfo)) {
                log.warn("UserTenantContextBuilder buildContext userTenantInfo is Empty");
                return;
            }
            String decryptUserInfo = AesUtils.decrypt(tenantInfo, appConfig.getSecretKey());
            YwuContext currentContext = YwuContextHolder.getCurrentContext();
            YwuContextTenant deserialize = GsonUtils.deserialize(decryptUserInfo, YwuContextTenant.class);
            currentContext.setYwuContextTenant(deserialize);
        } catch (Exception e) {
            log.error("UserTenantContextBuilder buildContext error {}", e.getMessage());
            throw new YwuRuntimeException(e.getMessage());
        }
    }

    @Override
    public String getBuildHeaderKey() {
        return TENANT_ID_HEADER_KEY;
    }
}
